package com.example.blog.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ControllerExceptionHandler {
//    获取日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
//    异常处理的注解拦截
    @ExceptionHandler(Exception.class)
//    控制返回页面加上后台返回的一些页面
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
//        这里是应用切面处理异常，并且将处理的内容加入到日志里
       logger.error("Request URL : {} , Exception : {}",request.getRequestURL(),e);
       if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
           throw e;
       }
       ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
//        获取异常信息
        mv.addObject("exception",e);
//        返回error页面
        mv.setViewName("/error/error");
       return mv;
    }
}
